package uk.co.richardwkirk.parkrun.android.dataload;

import uk.co.richardwkirk.parkrun.android.dataload.cache.NewsCache;
import uk.co.richardwkirk.parkrun.data.ParkrunDataLoadException;
import uk.co.richardwkirk.parkrun.news.NewsFeed;
import android.content.Context;
import android.util.Log;

public class NewsLoader extends ParkrunDataLoader {

	public class NewsFeedDataLoadAdapter implements LoadableParkrunDataAdapter {

		String url = null;
		NewsFeed news = null;

		public NewsFeedDataLoadAdapter(String newsFeedUrl, NewsFeed loadedNews) {
			this.url = newsFeedUrl;
			this.news = loadedNews;
		}

		@Override
		public void completeLoad() {
			// Cache the loaded news
			NewsCache.getSingleton().cache(url, news);
		}

	}

	String url = null;
	NewsFeedDataLoadAdapter loadedNews = null;

	public NewsLoader(Context context, String url) {
		super(context);
		this.url = url;
	}

	@Override
	protected void onStartLoading() {
		if (loadedNews != null) {
			deliverResult(loadedNews);
		} else {
			forceLoad();
		}
	}

	@Override
	public NewsFeedDataLoadAdapter loadInBackground() {
		try {
			// Have we cached this news feed?
			NewsFeed newsFeed = NewsCache.getSingleton().getItem(url);
			if (newsFeed == null) {
				// Load the news from the parkrun site.
				Log.d("PARKRUN", "Loading news feed: " + url);
				newsFeed = NewsFeed.loadNewsFeed(url);
			}
			loadedNews = new NewsFeedDataLoadAdapter(url, newsFeed);
			return loadedNews;
		} catch (ParkrunDataLoadException e) {
			Log.e("PARKRUN", "Could not load parkrun news feed", e);
			return null;
		}
	}

}
